import { TextWidget } from '@inbiz/react';
import { useEffect } from 'react';
import { useState } from 'react';
import { List } from 'antd';
import './style.less';

type Iprops = {
  dataList: {
    id: string | undefined;
    name: string;
  }[];
  relationOpt: (id: string | number | null) => void;
  searchWord: string;
  showKey: string;
  setSelectAndExpand: any;
  checkable: boolean;
};

const SearchList = (props: Iprops) => {
  const [currentId, $currentId] = useState<string | number | null>(null);
  const { dataList, relationOpt, searchWord, showKey, setSelectAndExpand, checkable } = props;

  useEffect(() => {
    $currentId(null);
  }, [props.dataList]);

  useEffect(() => {
    relationOpt(currentId);
    currentId && !checkable && setSelectAndExpand(searchWord?.length ? currentId : undefined, true);
  }, [currentId, searchWord]);

  useEffect(() => {
    return () => {
      relationOpt(currentId);
    };
  }, [currentId]);

  // 正则替换，关键词飘红
  function renderSearText(content: string) {
    let regStr = `(${searchWord})`;
    let reg = new RegExp(regStr, 'g');
    return content?.replace(
      reg,
      `<span style=color:var(--inbiz-color-primary)>${searchWord}</span>`,
    );
  }

  const select = (item: { id: string | number }) => {
    $currentId((origin) => {
      if (item.id == origin) {
        return null;
      } else return item.id;
    });
  };

  return (
    <List
      className="searchList"
      size="small"
      split={false}
      dataSource={dataList}
      locale={{
        emptyText: <TextWidget>pageselect.no_data</TextWidget>,
      }}
      renderItem={(item) => (
        <List.Item
          className={currentId == item.id ? 'currentItem' : 'item'}
          onClick={() => {
            select(item);
          }}
        >
          <span dangerouslySetInnerHTML={{ __html: renderSearText(item[showKey]) }}></span>
        </List.Item>
      )}
    />
  );
};
export default SearchList;
